<template>
  <div>
    <h1>商户列表</h1>
    <!-- 条件查询 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="用户名/真实姓名/手机号/邮箱"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.typeId"
            placeholder="请选择性别"
            clearable
          >
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间区间">
          <el-date-picker
            v-model="searchForm.beginTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          />
          <span>-</span>
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
          <el-button type="danger" @click="onDeleteBatch">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格数据 -->
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" width="80px" />
        <el-table-column prop="userName" label="登录账号" />
        <el-table-column prop="nickName" label="真实姓名" width="100px" />
        <el-table-column prop="gender" label="性别" width="80px">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.gender == 0">男</el-tag>
            <el-tag type="danger" v-if="scope.row.gender == 1">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userMobile" label="手机号" />
        <el-table-column prop="userEmail" label="邮箱" />
        <el-table-column prop="userAvatar" label="头像">
          <template #default="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.userAvatar"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="onShowEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="onDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 对话框---编辑 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="商户编辑" width="500">
        <el-form :model="form">
          <el-form-item label="登录账号" :label-width="formLabelWidth">
            <el-input v-model="form.userName" autocomplete="off" disabled />
          </el-form-item>
          <el-form-item label="真实姓名" :label-width="formLabelWidth">
            <el-input v-model="form.nickName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="form.userMobile" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="form.userEmail" autocomplete="off" />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" :value="0" />
              <el-option label="女" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:10010/auth/index/uploadImage"
              :show-file-list="false"
              :headers="headers"
              :on-success="handleAvatarSuccess"
            >
              <img
                v-if="form.userAvatar"
                :src="form.userAvatar"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmitEdit"> 提交 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getUserPage,
  updateUser,
  deleteByUserId,
  deleteBatch,
} from "../api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type UploadProps } from "element-plus";

const tableData = ref([]);
const searchForm = ref({
  beginTime: "",
  endTime: "",
  keyWord: "",
  pageNum: 1,
  pageSize: 2,
  typeId: null,
});
const total = ref(0);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
  gender: null,
  nickName: "",
  userAvatar: "",
  userEmail: "",
  userMobile: "",
  userName: "",
});

const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
};

const onDeleteBatch = () => {
  if (multipleSelection.value == null || multipleSelection.value.length == 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，确认删除吗?", "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消删除",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      deleteBatch(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          loadUserList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const onDelete = (row: any) => {
  ElMessageBox.confirm("删除后数据无法恢复，确认删除吗?", "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消删除",
    type: "warning",
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      deleteByUserId(row.userId).then((res) => {
        if (res.data.code == 200) {
          loadUserList();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const onSubmitEdit = () => {
  updateUser(form).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改完成");
      dialogFormVisible.value = false;
      loadUserList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const onShowEdit = (row: any) => {
  console.log("onShowEdit");
  Object.assign(form, row);
  dialogFormVisible.value = true;
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  form.userAvatar = response.data;
};

const headers = ref({
  token: sessionStorage.getItem("token"),
});

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadUserList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadUserList();
};

const onQuery = () => {
  console.log("submit!");
  loadUserList();
};

const loadUserList = () => {
  getUserPage(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadUserList();
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 条件搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
<!-- 头像样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
